/**
 * Created by wangshaohua on 2018/1/13.
 */
moduleLearningMap.controller("LearningMapDetail", function (LanguageService, LearningMapCourseResource, LearningMapRouteResource, QRCodeResource, $$CambioConfig, UploadFileService, $scope, $log, $state, $stateParams, GeneralResource, LoadingService, ConstantService, DialogService, BadgeResource, UriEventResource, DoorResource, OrganizationResource, LearningMapTemplateResource) {
        initPage($scope);
        $scope.$on("$viewContentLoaded", function () {
            //$scope.reset();
            pageOnLoad($scope);
            ConstantService.addState($state.current, true, LanguageService.language('学习地图详细'));
            $scope.learningMapId = $stateParams.learningMapId;
            $scope.selectTab('tabInfo');

            $scope.isPublish = false;

        });

        $scope.reloadPage = function () {
            $state.go('sz.learningMapDetail', {
                learningMapId: $scope.learningMapId
            });
        }


        $scope.currentTabId = 0;
        $scope.selectTab = function (tabId) {
            if (tabId === 'tabInfo') {
                $scope.loadDetail();
                $scope.currentTabId = tabId;
            }
            //
            if (tabId === 'tabRoute') {
                $scope.loadRoute();
                $scope.currentTabId = tabId;
            }
            if (tabId === 'tabCourse') {
                if ($scope.checkTab()) {
                    $scope.loadCourse();
                    $scope.currentTabId = tabId;
                }
            }
            if (tabId === 'tabBadge') {
                if ($scope.checkTab()) {
                    $scope.loadBadge();
                    $scope.currentTabId = tabId;
                }
            }
            if (tabId === 'tabUrlEvent') {
                if ($scope.checkTab()) {
                    $scope.loadUrlEvent();
                    $scope.currentTabId = tabId;
                }
            }
            if (tabId === 'tabPublish') {
                if ($scope.checkTab()) {
                    $scope.loadPublish();
                    $scope.currentTabId = tabId;
                }
            }
            if (tabId === 'tabDoor') {
                if ($scope.checkTab()) {
                    $scope.loadDoor();
                    $scope.currentTabId = tabId;
                }
            }
            //qrCode();
            if (tabId === 'tabQRCode') {
                if ($scope.checkTab()) {
                    qrCode();
                    $scope.currentTabId = tabId;
                }
            }
        };

        $scope.checkTab = function () {
            if ($scope.learningMapId) {
                return true;
            } else {
                Alert.error('请先填写基本信息，保存后才能操作！');
                return false;
            }
        }

        // ------------------------------------------------------------------------------------------------------

        $scope.queryPara = {
            className: Models.LearningMap.className
        };

        $scope.loadDetail = function () {
            //LoadingService.show();
            if ($scope.learningMapId) {
                GeneralResource.findById({id: $scope.learningMapId}, $scope.queryPara, function (queryResult) {
                    $log.debug("查询结果", queryResult.data);
                    $scope.learningMapDetail = queryResult.data;
                    //LoadingService.hide();
                });
            } else {
                //LoadingService.hide();
                $scope.learningMapDetail = {
                    picture: LearningMapTemplateUtils.findLearningMap().picture
                };
            }
        };

        $scope.loadLearningMapTemplates = function () {

        }

        $scope.selectLearningMapTemplate = function () {
            ConstantService.setItem('learningMapTemplate', $scope.selectedLearningMapTemplate);
        }

        $scope.saveLearningMapInfo = function () {
            Alert.confirm(function () {
                if ($scope.learningMapId) {
                    LearningMapTemplateResource.update({}, $scope.learningMapDetail, function () {
                        DialogService.close();
                        Alert.success();
                        //LoadingService.hide();
                    });
                }
            });
            //GeneralResource.save({}, $scope.learningMapDetail, function () {
        };

        // ------------------------------------------------------------------------------------------------------
        // ------------------------------------------------------------------------------------------------------

        $scope.loadCourse = function () {
            $scope.queryCoursePara = {
                className: Models.LearningMapCourse.className,
                query: {
                    p1: {
                        field: Models.LearningMapCourse.query.learningMapId,
                        value: $scope.learningMapId
                    }
                }
            };

            //LoadingService.show();
            GeneralResource.queryPage({pageNo: 0, pageSize: 40}, $scope.queryCoursePara, function (result) {
                $log.debug("查询结果", result.data.datas);
                $scope.courses = result.data.datas;
                //LoadingService.hide();
            });
        }

        $scope.openCourseDetail = function (record) {
            $state.go("sz.learningMapCourseDetail", {
                learningMapCourseId: record.id,
                learningMapId: $scope.learningMapId
            });
        }

        $scope.newCourseDetail = function () {
            var sort = 1;
            if ($scope.courses) {
                sort = $scope.courses.length + 1
            }
            $scope.learningMapCourseDetail = {
                learningMapId: $scope.learningMapId,
                picture: LearningMapTemplateUtils.findCourse().picture,
                sort: sort
            };
            DialogService.open("addLearningMapCourse", $scope, function () {
                $scope.loadCourse();
            });
        }

        $scope.publishCourse = function (course) {
            Alert.confirm(function () {
                //LoadingService.show();
                LearningMapCourseResource.publish({}, course, function () {
                    DialogService.close();
                    Alert.success();
                    $scope.loadCourse();
                    //LoadingService.hide();
                });
            });
        }

        $scope.removeCourse = function (course) {
            Alert.confirm(function () {
                //LoadingService.show();
                LearningMapCourseResource.remove({id: course.id}, {}, function () {
                    // DialogService.close();
                    Alert.success();
                    $scope.loadCourse();
                    //LoadingService.hide();
                });
            });
        }


        // ------------------------------------------------------------------------------------------------------
        // ------------------------------------------------------------------------------------------------------

        $scope.loadBadge = function () {
            //LoadingService.show();
            BadgeResource.findByLearningMapId({learningMapId: $scope.learningMapId}, {}, function (result) {
                $log.debug("查询结果", result.data);
                $scope.badges = result.data;
                //$scope.pagination.setPage(queryResult.data, pageNo);
                //LoadingService.hide();
            });
        }

        $scope.addBadge = function () {
            $scope.currentConfig = {};
            DialogService.open("configBadgeForCourse", $scope, $scope.loadBadge);
        }

        $scope.removeBadge = function (badge) {
            Alert.confirm(function () {
                //LoadingService.show();
                BadgeResource.remove({id: badge.id}, {}, function (result) {
                    $log.debug("查询结果", result.data);
                    $scope.loadBadge();
                    Alert.success();
                    //LoadingService.hide();
                });
            });
        }


        // ------------------------------------------------------------------------------------------------------
        // ------------------------------------------------------------------------------------------------------

        $scope.loadPublish = function () {
            //LoadingService.show();
            OrganizationResource.publishOrganizationByLearningMapId({learningMapId: $scope.learningMapId}, {}, function (result) {
                $log.debug("查询结果", result.data);
                $scope.publishOrganization = result.data;
                //$scope.pagination.setPage(queryResult.data, pageNo);
                //LoadingService.hide();
            });
        }


        $scope.selectAllRightCustomer = function () {
            if ($scope.publishOrganization.notExists) {
                for (var i = 0; i < $scope.publishOrganization.notExists.length; i++) {
                    $scope.publishOrganization.notExists[i].checked = $scope.checkNotExistsAll;
                }
            }
        }

        $scope.selectAllLeftCustomer = function () {
            if ($scope.publishOrganization.exists) {
                for (var i = 0; i < $scope.publishOrganization.exists.length; i++) {
                    $scope.publishOrganization.exists[i].checked = $scope.checkExistsAll;
                }
            }
        }

        $scope.addPublishOrganization = function () {
            if (!$scope.publishOrganization.notExists) {
                return null;
            }
            var records = $scope.publishOrganization.notExists;
            var uncheckRecords = new Array();
            for (var i = 0, len = records.length; i < len; i++) {
                if (records[i].checked) {
                    records[i].checked = false;
                    $scope.publishOrganization.exists.push(records[i]);
                } else {
                    uncheckRecords.push(records[i]);
                }
            }
            $scope.publishOrganization.notExists = uncheckRecords;
        }

        $scope.removePublishOrganization = function () {
            if (!$scope.publishOrganization.exists) {
                return null;
            }
            var records = $scope.publishOrganization.exists;
            var uncheckRecords = new Array();
            for (var i = 0, len = records.length; i < len; i++) {
                if (records[i].checked) {
                    records[i].checked = false;
                    $scope.publishOrganization.notExists.push(records[i]);
                } else {
                    uncheckRecords.push(records[i]);
                }
            }
            $scope.publishOrganization.exists = uncheckRecords;
        }

        $scope.publishForOrganization = function () {
            Alert.confirm(function () {
                //LoadingService.show();
                LearningMapTemplateResource.publishForOrganization({learningMapId: $scope.learningMapId}, {}, function (result) {
                    $log.debug("查询结果", result.data);
                    //$scope.loadBadge();
                    Alert.success();
                    //LoadingService.hide();
                });
            });
        }

        $scope.publish = function () {
            Alert.confirm(function () {

                var organizationIds = new Array();
                if ($scope.publishOrganization.exists && $scope.publishOrganization.exists.length > 0) {
                    for (var i = 0; i < $scope.publishOrganization.exists.length; i++) {
                        organizationIds.push($scope.publishOrganization.exists[i].id);
                    }
                }

                var bean = {
                    learningMapId: $scope.learningMapId,
                    all: $scope.publishOrganization.all,
                    organizationIds: organizationIds
                };
                //LoadingService.show();
                LearningMapTemplateResource.publish({}, bean, function (result) {
                    $log.debug("查询结果", result.data);
                    //$scope.loadBadge();
                    Alert.success();
                    //LoadingService.hide();
                });
            });
        }

// ------------------------------------------------------------------------------------------------------

        $scope.loadUrlEvent = function () {
            //LoadingService.show();
            UriEventResource.findByLearningMapId({learningMapId: $scope.learningMapId}, {}, function (result) {
                $log.debug("查询结果", result.data);
                $scope.urlEventResults = result.data;
                UUID.format($scope.urlEventResults);
                //$scope.pagination.setPage(queryResult.data, pageNo);
                //LoadingService.hide();
            });
        }

        $scope.addUrlEvent = function () {
            $scope.currentConfig = {};
            DialogService.open("configUriEventForCourse", $scope, $scope.loadUrlEvent);
        }

        $scope.removeUrlEvent = function (urlEvent) {
            Alert.confirm(function () {
                //LoadingService.show();
                UriEventResource.remove({id: urlEvent.id}, {}, function (result) {
                    $log.debug("查询结果", result.data);
                    $scope.loadUrlEvent();
                    Alert.success();
                    //LoadingService.hide();
                });
            });
        }


// ------------------------------------------------------------------------------------------------------

        $scope.loadDoor = function () {
            //LoadingService.show();
            DoorResource.findByLearningMapId({learningMapId: $scope.learningMapId}, {}, function (result) {
                $log.debug("查询结果", result.data);
                $scope.doors = result.data;
                UUID.format($scope.doors);
                //$scope.pagination.setPage(queryResult.data, pageNo);
                //LoadingService.hide();
            });
        }

        $scope.addDoor = function () {
            $scope.currentConfig = {};
            DialogService.open("configDoorForCourse", $scope, $scope.loadDoor);
        }

        $scope.removeDoor = function (door) {
            Alert.confirm(function () {
                //LoadingService.show();
                DoorResource.remove({id: door.id}, {}, function (result) {
                    $log.debug("查询结果", result.data);
                    $scope.loadDoor();
                    Alert.success();
                    //LoadingService.hide();
                });
            });
        }

// ------------------------------------------------------------------------------------------------------

        $scope.uploadImage = function ($files) {
            if ($files && $files[0]) {
                UploadFileService.uploadFile($files[0], $$CambioConfig.UPLOAD_URL, 'IMG', $scope).then(function (o) {
                    $scope.learningMapDetail.picture = o.id;
                });
            }
        };

// ------------------------------------------------------------------------------------------------------

        var qrCode = function () {
            const qrCodeBean = {
                id: $scope.learningMapId,
                fieldName: "STUDY_MAP_ID",
                newParams: $scope.urlParams
            };
            QRCodeResource.getProductQRCode({}, qrCodeBean, function (urlResult) {
                $log.debug("产品二维码结果", urlResult);
                $('#qrcode').empty();
                $('#qrcode').qrcode({width: 128, height: 128, text: urlResult.rawUrl});
                $scope.profileUrl = urlResult.value;
                $scope.rawUrl = urlResult.rawUrl;
            });
        };

        $scope.urlParams = {};
        $scope.urlParamsString = JSON.stringify($scope.urlParams);
        $scope.newParam = {};
        $scope.addParam = function () {
            if (!StringUtils.isNlOrUndOrEmpty($scope.newParam.key) && !StringUtils.isNlOrUndOrEmpty($scope.newParam.value)) {
                $scope.urlParams[$scope.newParam.key] = $scope.newParam.value;
                $scope.urlParamsString = JSON.stringify($scope.urlParams);
                $scope.newParam = {};
            }
        };

        $scope.resetParam = function () {
            $scope.urlParams = {};
            $scope.urlParamsString = JSON.stringify($scope.urlParams);
        };

        $scope.reCreate = function () {
            qrCode();
        };

// ------------------------------------------------------------------------------------------------------

        $scope.loadRoute = function () {
            //LoadingService.show();
            LearningMapRouteResource.findByLearningMapId({learningMapId: $scope.learningMapId}, {}, function (result) {
                $log.debug("查询结果", result.data);
                $scope.learningMapRoute = result.data;
                //LoadingService.hide();
            });
            //$scope.learningMapId
        }

        $scope.addRoute = function () {
            $scope.currentConfig = {
                learningMapId: $scope.learningMapId
            };
            DialogService.open("configRouteForMap", $scope, function () {
                $scope.loadRoute();
            });
            //$scope.learningMapId
        }

        $scope.editRoute = function () {
            $scope.currentConfig = $scope.learningMapRoute;
            DialogService.open("configRouteForMap", $scope, function () {
                $scope.loadRoute();
            });
            //$scope.learningMapId
        }


// ------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------------

        $scope.betweenTime = function (record) {
            if (record.longTime) {
                return LanguageService.language('不限时间');
            } else {
                return record.startTime.toDateTime() + "-" + record.endTime.toDateTime();
            }
        }


//$scope.openDetail = function(record){
//    $state.go( "sz.homepage",{
//        learningMapId: record.id
//    });
//}
//$scope.query($scope.pagination.currentPageNo);

//$scope.addStudyMap = function () {
//    DialogService.open("addStudyMap");
//};
//
//$scope.editStudyMap = function (studyMap) {
//    $scope.currentStudyMap = studyMap;
//    DialogService.open("editStudyMap", $scope);
//};

//$scope.setupClassGroup = function (studyMap) {
//    ConstantService.setItem("currentStudyMapId", studyMap.id);
//    $state.go("sz.studyMap.classGroup");
//};
//
//$scope.toRoute = function (map) {
//    $scope.currentStudyMap = map;
//    DialogService.open("setStudyMapRoute", $scope);
//};
//
//$scope.clearUserStudy = function (studyMap) {
//    Alert.confirm("是否确认要执行该操作？", function () {
//        var bean = {
//            studyMapId: studyMap.id
//        };
//        UserStudyResource.clearForStudyMap(bean, {}, function () {
//            $log.debug("清理用户信息");
//            DialogService.close();
//            Alert.success("清理用户信息成功！");
//            //LoadingService.hide();
//        });
//    });
//};
//
//$scope.clone = function(studyMap){
//    Alert.confirm(function () {
//        var bean = {
//            studyMapId: studyMap.id
//        };
//        StudyMapResource.clone({}, bean, function () {
//            $log.debug("清理用户信息");
//            DialogService.close();
//            Alert.success();
//            //LoadingService.hide();
//        });
//    });
//}
//
//$scope.updateProductStatus = function (map, productStatus) {
//    var bean = {
//        id: map.id,
//        status: productStatus,
//        type: "STUDY_MAP_ID"
//    };
//    ProductResource.updateStatus({}, bean, function () {
//        $log.debug("更新产品状态");
//        DialogService.close();
//        Alert.success("更新产品状态成功！");
//        //LoadingService.hide();
//    }, function () {
//        //LoadingService.hide();
//    })
//}
//
//$scope.refresh = function () {
//    $scope.queryPara = {};
//};
//
//$scope.toQRCode = function (map) {
//    $scope.qrCodeBean = {
//        id: map.id,
//        fieldName: "STUDY_MAP_ID"
//    };
//    DialogService.open("productQRCode", $scope);
//}
    }
)
;